<?php
/**
 * Created by PhpStorm.
 * User => guokunsheng
 * Date => 2020/10/13
 * Time => 10 =>13
 */

namespace app\astrologer\controller;

use app\common\cachemodel\ZlcrAstrAccount;
use app\common\cachemodel\ZlcrCustomReportQuestion;
use app\common\cachemodel\ZlcrCustomReportQuestionComment;
use think\Db;

/**
 * Class Earnings
 * @support v1.0.0
 * @package app\astrologer\controller
 */
class Earnings extends AstrAuth
{

    /**
     * 收益统计信息
     * @method GET
     */
    public function index()
    {
        $param = $this->request->only(['is_this_month']);

        $accountInfo = (new ZlcrAstrAccount())->getAstrAccountInfo($this->astrInfo['id'], ['total_amount', 'month_earnings', 'last_month_earnings']);

        $data = [
            'last_month_earings' => (float)$accountInfo['last_month_earnings'],
            'this_month_earings' => (float)$accountInfo['month_earnings'],
            'total_earings' => (float)$accountInfo['total_amount'],
        ];

        return show(200, '请求成功', $data);
    }

    /**
     * 获取列表数据
     * @method GET
     */
    public function list()
    {
        $param['page'] = $this->request->param('page/d', 1);
        $param['limit'] = $this->request->param('limit/d', 10);
        //h5
        $param['start_time'] = $this->request->param('start_time/s', 0);
        $param['end_time'] = $this->request->param('end_time/s', 0);
        //pc
        $rangeTime = input('range_time/a', []);
        $param['question'] = $this->request->param('question/s', '');
        $param['qtype'] = $this->request->only(['qtype']);
        $param['status'] = $this->request->only(['status']);

        $where = [
            'q.astr_id' => $this->astrInfo['id'],
        ];

        if (!empty($rangeTime))
        {
            if (!empty($rangeTime[0]) && !empty($rangeTime[1]))
            {
                // 前端组件，肯定有这两个参数
                $where['a.create_time'] = ['between', [strtotime($rangeTime[0]), strtotime($rangeTime[1])]];
            }
        } else if (($param['start_time'] && $param['end_time']))
        {
            $start_time = strtotime($param['start_time']);
            $end_time = strtotime($param['end_time']);
            if ($end_time < $start_time)
            {
                return show(0, '开始时间不能大于结束时间！');
            } else
            {
                $where['a.create_time'] = ['between', [$start_time, $end_time]];
            }

        } else if ($param['start_time'])
        {
            $start_time = strtotime($param['start_time']);
            $where['a.create_time'] = ['>=', $start_time];
        } else if ($param['end_time'])
        {
            $where['a.create_time'] = ['<', strtotime($param['start_time'])];
        }

        if ($param['qtype'])
        {
            foreach ($param['qtype']['qtype'] as $k => $v)
            {
                $qtype['qtype']['qtype'][$k] = (int)$v;
            }
            $where['q.qtype'] = ['in', $qtype['qtype']['qtype']];
        }

        if ($param['status'])
        {
            if (is_array($param['status']['status']))
            {
                foreach ($param['status']['status'] as $k => $v)
                {
                    $param['status']['status'][$k] = (int)$v;
                }
                if ($param['status']['status'][0] === 5)
                {//如果是已完成，那么把评价待审核和已评价也加上
                    $param['status']['status'][] = 6;
                    $param['status']['status'][] = 7;
                }
                $where['q.status'] = ['in', $param['status']['status']];
            } else
            {
                $status = [];
                foreach ($param['status'] as $k => $v)
                {
                    $status[] = (int)$v;
                }
                if ($status[0] === 5)
                {//如果是已完成，那么把评价待审核和已评价也加上
                    $status[] = 6;
                    $status[] = 7;
                }
                $where['q.status'] = ['in', $status];
            }

        }

        if ($param['question'])
        {
            $where['q.question_name'] = ['like', '%' . $param['question'] . '%'];
        }

        $resData = Db::table('wechat_backup_07_18_14_43_00.zlcr_custom_report_question')->alias('q')
            ->join('wechat_backup_07_18_14_43_00.zlcr_astr_account_record a', 'a.qid=q.id')
            ->where($where)->order('a.create_time desc')
            ->field('q.id qid,q.question_name question,q.astr_receiving_time,a.amount earnings,q.status,q.qtype,q.is_merge,q.is_back,q.check_time1,q.check_time2,q.answer_time,a.proportion,q.invalid_time,a.type zlcr_astr_account_record_type')
            ->paginate(['page' => $param['page'], 'list_rows' => $param['limit']])->toArray();

        //todo 遍历处理，把 占星师的回答问题 部分的收益，改为0
        if (isset($resData['data']))
        {
            foreach ($resData['data'] as $k => $v)
            {
                if ((int)$v['zlcr_astr_account_record_type'] === 3)
                {
                    $resData['data'][$k]['earnings'] = 0;
                    $resData['data'][$k]['status'] = 17;
                }
                unset($resData['data'][$k]['zlcr_astr_account_record_type']);
            }
        }

//        $qids = array_column($resData['data'], 'qid');
        // $commentList = (new ZlcrCustomReportQuestionComment())->alias('c')->join('wechat_backup_07_18_14_43_00.zlcr_tag t', 'c.tid=t.id')->whereIn('c.qid', $qids)->column('c.level,c.tid,c.status,c.comment,c.appeal_status,c.create_time,t.tag_name tname', 'c.qid');
//        $commentList = (new ZlcrCustomReportQuestionComment())->alias('c')->join('wechat_backup_07_18_14_43_00.zlcr_tag t', 'c.tid=t.id')->whereIn('c.qid', $qids)->column('c.level,c.tid,t.tag_name tname', 'c.qid');

//        foreach ($resData['data'] as $key => $dataItem)
//        {
//            // $resData['data'][$key]['comment_data'] = null;
//            // if ((int)$dataItem['status'] === 7 && isset($commentList[$dataItem['qid']]))
//            // {
//            //     if ($commentList[$dataItem['qid']]['appeal_status'])
//            //     {
//            //         $level = 3;
//            //         $comment = '平淡无味';
//            //     } else
//            //     {
//            //         $level = (int)$commentList[$dataItem['qid']]['level'];
//            //         $comment = (int)$commentList[$dataItem['qid']]['status'] === 3 ? '' : $commentList[$dataItem['qid']]['comment'];
//            //     }
//            //     $resData['data'][$key]['comment_data'] = [
//            //         'level' => $level,
//            //         'comment' => $comment,
//            //         'create_time' => (int)$commentList[$dataItem['qid']]['create_time'],
//            //         'tname' => $commentList[$dataItem['qid']]['tname'],
//            //     ];
//            // }
//            if ((int)$dataItem['status'] === 7 && isset($commentList[$dataItem['qid']]))
//            {
//                $resData['data'][$key]['rate'] = (int)$commentList[$dataItem['qid']]['level']; // 标签星级
//                $resData['data'][$key]['tname'] = $commentList[$dataItem['qid']]['tname']; // 标签名字
//            } else
//            {
//                $resData['data'][$key]['rate'] = 0;
//                $resData['data'][$key]['tname'] = '';
//            }
//        }
        // [
        //     'order_id' => '05202009232113575966',
        //     'question' => '1我今年的爱情运势？',
        //     'astr_receiving_time' => 1601192261,// 接单时间
        //     'earnings' => '179.70',
        //     'status' => 7,
        //     'qtype' => 1,
        //     'is_merge' => 1,
        //     'is_back' => 0,
        //     'check_time1' => 1601192261,// 问题审核时间
        //     'check_time2' => 1601192362,// 回答后审核时间
        //     'answer_time' => 1601197261,// 解答时间
        //     'tname' => '', //标签名字
        //     'proportion'=>0.3 // 收益比例 0.3=>30%
        //     'rate' => 4,
        //     'fadeback' => '算的好准，希望能帮助更多的人！',
        //     'desc' => '爱情里，真的能让人深刻感受到被爱的，只有“偏爱”，有句话说如果你给我的是和别人一样的，那我宁愿不要。所以如果男人是真心的爱着你，只要是关于你的事情，他都会偏袒你，大到生活，小到微信。',
        // ]

        return show(200, '请求成功', $resData);
    }

    /**
     * 收益申诉
     * @method POST
     */
    public function complain()
    {
        $id = input('id/d', 0);

        $data = [];

        return show(200, '请求成功', $data);
    }

    /**
     * 提现列表
     */
    public function getWithdrawalList()
    {
        $isTeam = input('is_team/d', 0);

        $teamId = $this->astrInfo['team_id'] ?? 0;
        if ($isTeam === 1 && !$teamId)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $zlcrAstrAccountModel = new ZlcrAstrAccount();
        $accountInfo = $zlcrAstrAccountModel->getAstrAccountInfo($this->astrInfo['id'], ['balance', 'total_amount']);

        if ($isTeam === 1)
        {
            $resData1 = Db::table('good_wechat.zyhs_astr_account_withdrawal_record')
                ->where(['astr_id' => $this->astrInfo['id'], 'is_withdrawal' => 1, 'type' => 2, 'team_id' => $teamId])
                ->order('withdrawal_time desc')
                ->column('date,astr_earnings,income_tax,after_tax_income,withdrawal_time,2 as type', 'id');
            $resData2 = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')
                ->where(['astr_id' => $this->astrInfo['id'], 'is_withdrawal' => 1, 'type' => 2, 'is_emergency' => 0, 'team_id' => $teamId])
                ->order('withdrawal_time desc')
                ->field("date,astr_earnings,income_tax,after_tax_income,withdrawal_time,id,1 as type")->select();
            $resData = array_merge($resData1, $resData2);
            $sort = array_column($resData, 'withdrawal_time');
            array_multisort($sort, SORT_DESC, $resData);
        } else
        {
            $resData1 = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')
                ->where(['astr_id' => $this->astrInfo['id'], 'is_withdrawal' => 1, 'is_emergency' => 0, 'team_id' => 0])
                ->order('withdrawal_time desc')
                ->field("date,astr_earnings,income_tax,after_tax_income,withdrawal_time,id,1 as type")->select();
            $resData2 = Db::table('good_wechat.zyhs_astr_account_withdrawal_record')
                ->where(['astr_id' => $this->astrInfo['id'], 'is_withdrawal' => 1, 'type' => 1, 'team_id' => 0])
                ->order('withdrawal_time desc')
                ->field("id,date,astr_earnings,income_tax,after_tax_income,withdrawal_time,2 as type")->select();

            $resData = array_merge($resData1, $resData2);
            $sort = array_column($resData, 'withdrawal_time');
            array_multisort($sort, SORT_DESC, $resData);
        }

        foreach ($resData as $key => $datum)
        {
            // $resData[$key]['withdrawal_type'] = '系统自动提现';
            $resData[$key]['withdrawal_time'] = date('m月d日', $datum['withdrawal_time']); // 提现打款时间
            $resData[$key]['date'] = date('Y-m月', strtotime($datum['date'])); // 申请提现时间
            // 当前只显示已打款数据
            $resData[$key]['status_des'] = $isTeam === 1 ? '已打款至团队' : '已打款';
            $resData[$key]['status'] = 1;
            $resData[$key]['id'] = (int)$datum['id'];
            $resData[$key]['type'] = (int)$datum['type'];
            if ($teamId)
            {   // 团队身份
                $des = ((int)$datum['type'] === 1 ? '准了问答、准了连线咨询' : '准有好事连线咨询、准有好事问答');
            } else
            {   // 个人身份
                $des = '问答、定制报告';
            }
            $resData[$key]['des_list'] = [
                '结算月份：' . $resData[$key]['date'],
                '结算金额：¥' . $datum['astr_earnings'],
                '实际到账：¥' . $datum['after_tax_income'],
                '收益来源：' . $des,
            ];
        }

        // 计算团队 至今总收益 以及 未提现金额
        if ($teamId)
        {   // 团队 占星师个人 总收益
            $teamTotalAmount = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->where(['astr_id' => $this->astrInfo['id'], 'type' => 1, 'team_id' => $teamId])->sum('amount');
            // 团队 占星师个人 未提现总余额
            $teamBalance = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->where(['astr_id' => $this->astrInfo['id'], 'type' => 1, 'team_id' => $teamId, 'is_withdrawal' => 0])->sum('amount');
        } else
        {
            $teamTotalAmount = 0;
            $teamBalance = 0;
        }

        if ($isTeam === 1)
        {   // 未结算
            $balance = $teamBalance;
            $totalAmount = $teamTotalAmount;
        } else
        {
            $balance = $accountInfo['balance'] - $teamBalance; // 当前余额 - 团队未结算金额 =  个人余额（个人未结算金额）
            $totalAmount = $accountInfo['total_amount'] - $teamTotalAmount; // 当前总收益 - 团队个人总收益 = 个人结算中总收益
        }

        return show(config('code.success'), '请求成功', [
            'balance' => (string)$balance,   // 未结算
            'earn_all' => (string)$totalAmount, // 总收益
            'withdrawal_list' => array_values($resData),
            'is_team' => $teamId > 0 ? 1 : 0,
        ]);
    }
}
